package com.apes.hr.paySupport.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.outbox.OutboxSubscriberService;
import com.apes.framework.query.SqlService;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.hr.base.model.Employee;
import com.apes.hr.base.model.WorkPost;
import com.apes.hr.base.repository.EmployeeRepository;
import com.apes.hr.paySupport.model.*;
import com.apes.hr.paySupport.repository.SupportApplicationDetailRepository;
import com.apes.hr.paySupport.repository.SupportApplicationExecutionRepository;
import com.apes.hr.paySupport.repository.SupportApplicationItemRepository;
import com.apes.hr.paySupport.repository.SupportApplicationRepository;
import com.apes.hr.transfer.model.TransferApplicationItem;
import com.apes.hr.transfer.repository.TransferApplicationItemRepository;
import com.apes.hr.transfer.repository.TransferApplicationRepository;
import com.apes.hr.transfer.service.TransferApplicationService;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.rbac.model.Post;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.PostRepository;
import com.apes.scm.rbac.repository.UserRepository;
import com.apes.scm.rbac.service.UserService;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Title: SupportApplicationService
 * @Description: 付费支援申请单
 * @author: ZhengZeXian
 * @create: 2021/4/15 14:26
 */
@Service("hrSupportApplicationService")
public class SupportApplicationService extends DomainService {

    @Autowired
    private SupportApplicationRepository supportApplicationRepository;
    @Autowired
    private SupportApplicationItemRepository supportApplicationItemRepository;
    @Autowired
    private SupportApplicationDetailRepository supportApplicationDetailRepository;
    @Autowired
    private SupportApplicationExecutionRepository supportApplicationExecutionRepository;
    @Autowired
    private PostRepository postRepository;
    @Autowired
    private TransferApplicationService transferApplicationService;
    @Autowired
    private TransferApplicationRepository transferApplicationRepository;
    @Autowired
    private TransferApplicationItemRepository transferApplicationItemRepository;
    @Autowired
    private DeptRepository deptRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserService userService;
    @Autowired
    private SqlService sqlService;
    @Autowired
    private EmployeeRepository employeeRepository;
    @Autowired
    private EnumerationRepository enumerationRepository;


    /**
     * 获取支援人员明细
     */
    public Map getSupportEmployee(SimpleRequest request){
        JSONObject param = request.getJO();
        //获取当前行的计费支援单执行表ID
        String id = param.getJSONObject("node").getString("SUPPORT_EXEC_ID");
        SupportApplicationExecution exec = supportApplicationExecutionRepository.findOne(id);
        SupportApplicationItem item = exec.getSupportApplicationItem();
        return MapUtil.mapper(
                "id", item.getSupportApplication().getId(),
                "employee", item.getSupportUid(),
                "postAfter", exec.getWorkPost(),
                "branch", item.getBranch(),
                "branchAfter", item.getBranchAfter(),
                "supportNature", item.getHrTransferKind().getDescription(),
                "driving", item.isDriver() == true ? "是" : "否",
                "startDate", DateUtil.format(exec.getStartDate(),"YYYY-MM-dd"),
                "startTime", exec.getStartTime().getDescription(),
                "endDate", DateUtil.format(exec.getEndDate(),"YYYY-MM-dd"),
                "endTime", exec.getEndTime().getDescription(),
                "supportDays", exec.getSupportDays(),
                "tollCase", exec.isTollCase() == true ? "收费" : "免费",
                "tollAmt", exec.getTollAmt(),
                "discountsAmt", exec.getDiscountsAmt(),
                "actualPayAmt", exec.getActualPayAmt()
        );
//        JSONObject object = new JSONObject(map);
//        return MapUtil.mapper(
//                "content", object,
//                "total", object.size(),
//                "size",  object.size()
//        );
    }

    public List<Map> queryStaffing(SimpleRequest request){
        JSONObject jsonObject = request.getJO();
        JSONObject param = new JSONObject();
        Map workPost = (Map) JSON.parse(jsonObject.getString("workPost"));
        if(jsonObject.getString("dept") != null){
            Map map = (Map) JSON.parse(jsonObject.getString("dept"));
            Dept dept = deptRepository.findOne(map.get("id").toString());
            param.put("BRANCH_ID",dept.getBranch().getId());
        }
        param.put("WORK_POST_ID",workPost.get("id"));
        com.apestech.framework.json.JSONArray array = sqlService.queryId("staffing.query", new com.apestech.framework.json.JSONObject(param));
        com.alibaba.fastjson.JSONArray jsonArray = JSONObject.parseArray(String.valueOf(array));
        List<Map> maps = JSONObject.parseArray(jsonArray.toJSONString(), Map.class);
        //自定义排序 返回-1 排序到最前面
        Collections.sort(maps, new Comparator<Map>() {
            @Override
            public int compare(Map o1, Map o2) {
                if(o1.get("BRANCH_ID").equals("1001030500") || o1.get("BRANCH_ID").equals("00000161")){
                    return -1;
                }
                return 1;
            }
        });
        return maps;
    }

    public List<Employee> getStaffingEmployee(SimpleRequest request){
        String BRANCH_ID = request.get("BRANCH_ID");
        String WORK_POST_ID = request.get("WORK_POST_ID");
        List<Employee> employees = employeeRepository.findByWorkBranchIdAndPostId(BRANCH_ID, WORK_POST_ID);
        return employees;
    }

    public SupportApplication findById(SimpleRequest request){
        String support_application_id = request.get("SUPPORT_APPLICATION_ID");
        return supportApplicationRepository.findOne(support_application_id);
    }

    public Enumeration findOperation(SimpleRequest request){
        String id = request.get("id");
        return supportApplicationRepository.findOperation(id);
    }

    public Enumeration findFnTag(SimpleRequest request){
        String id = request.get("id");
        return supportApplicationRepository.findFnTag(id);
    }

    /***
     * 功能： 用于处理返回值
     * @param lists
     * @return
     */
    protected JSONArray toJSONArray(List<Map> lists) {
        JSONArray returnArr = new JSONArray();
        lists.stream().forEach(list -> returnArr.add(new JSONObject(list)));
        return returnArr;
    }

    public SupportApplication save(SimpleRequest request){
        SupportApplication supportApplication = request.getO(SupportApplication.class);
        if(supportApplication.getSupportApplicationDetails().size() > 1){
            throw new RuntimeException("计费支援单" + supportApplication.getId() + "只允许同时申请一个岗位，请检查！！！");
        }
        SupportApplicationDetail detail = supportApplication.getSupportApplicationDetails().get(0);
        Post post = postRepository.findOne(request.getPostId());
        supportApplication.setCompany(post.getCompany());
        supportApplication.setDept(post.getDept());
        supportApplication.setState("create");
        supportApplication.setCreateUid(request.getPerson());
        return supportApplicationRepository.saveAndFlush(supportApplication);
    }

    public SupportApplication update(SimpleRequest request){
        checkData(request);
        SupportApplication supportApplication = request.getO(SupportApplication.class);
        if(supportApplication.getSupportApplicationDetails().size() > 1){
            throw new RuntimeException("计费支援单" + supportApplication.getId() + "只允许同时申请一个岗位，请检查！！！");
        }
        return supportApplicationRepository.saveAndFlush(supportApplication);
    }

    public String delete(SimpleRequest request){
        checkData(request);
        SupportApplication supportApplication = request.getO(SupportApplication.class);
        supportApplication.setState("delete");
        supportApplicationRepository.saveAndFlush(supportApplication);
        return "删除成功！";
    }

    /**
     * 转审核
     * @param request
     * @return
     */
    public SupportApplication transApprove(SimpleRequest request){
        SupportApplication supportApplication = request.getO(SupportApplication.class);
        supportApplication.setState("transApprove");
        getCandidate(supportApplication);
        return supportApplicationRepository.saveAndFlush(supportApplication);
    }

    /**
     * 审核 支援单
     * @param request
     * @return
     */
    public SupportApplication approve(SimpleRequest request){
        SupportApplication requestO = request.getO(SupportApplication.class);
        if (requestO.getSupportApplicationItems().isEmpty()) throw new RuntimeException("请填写支援人员明细");
        checkSupportApplicationRoles(requestO);   //检查支援人员本地角色
        checkTransferClash(requestO);             //检查与调动单和支援单是否有冲突

        SupportApplication supportApplication = supportApplicationRepository.saveAndFlush(requestO);

        //判断当前时间是上午还是下午 结果为“0”是上午 结果为“1”是下午
        GregorianCalendar ca = new GregorianCalendar();
        int i = ca.get(GregorianCalendar.AM_PM);
        String time = i == 0 ? "AM" :"PM";

        //执行内容
        List<SupportApplicationExecution> listExec = new ArrayList();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String sToday = format.format(new Date());

        List<SupportApplicationItem> items = supportApplication.getSupportApplicationItems();
        items.forEach(item -> {
            Date startDate = item.getStartDate();//开始日期
            String sStartDate = format.format(startDate);

            insertExecution(item);  //将支援单写入执行表

            User user = userRepository.findByOrigin(item.getSupportUid().getOrigin());
            if (user!=null){
                // 更新要备份 的 原 item 角色 列表
                List<Post> postLists = user.getPosts();
                if (postLists.size()>0) {
                    List<Post> posts = new ArrayList<>();
                    StringBuffer yRoleList = new StringBuffer();
                    postLists.forEach(yRole -> {
                        yRoleList.append(yRole.getId()+";");
                    });
                    supportApplicationItemRepository.updateItemRoles(yRoleList.toString(),item.getId().toString());
                }
            }

            //如果不是今天的，执行标识为否
            if (!sToday.equals(sStartDate)){
                item.setIconExecute(false);
                return;
            }
            //如果开始日期是今天的，但开始时间不符的，执行标识为否
            if (sToday.equals(sStartDate) && !item.getStartTime().getCode().equals(time)){
                item.setIconExecute(false);
                return;
            }
            if (!item.isRepeal()){
                SupportApplicationExecution iExec = new SupportApplicationExecution();
                iExec.setSupportApplicationItem(item);
                iExec.setSupportUid(item.getSupportUid());
                iExec.setBranch(item.getBranchAfter());
                iExec.setWorkPost(item.getWorkPostAfter());
                iExec.setStartDate(item.getStartDate());
                iExec.setEndDate(item.getEndDate());
                listExec.add(iExec);
            }
        });

        if(listExec.size()>0)updateRYXX(listExec);//参数 :更新列表，是否扣减待调人数：不扣

        supportApplication.setState("done");
        supportApplication.setApproveDate(new Date());
        supportApplication.setApproveUid(request.getPerson());
        return supportApplicationRepository.saveAndFlush(supportApplication);
    }

    /**
     * 审核拒绝
     * @param request
     * @return
     */
    public SupportApplication refuse(SimpleRequest request){
        SupportApplication supportApplication = request.getO(SupportApplication.class);
        supportApplication.setState("repeal");
        supportApplication.getSupportApplicationItems().forEach(supportApplicationItem -> supportApplicationItem.setRepeal(true));
        return supportApplicationRepository.saveAndFlush(supportApplication);
    }

    /**
     * 过期审核
     */
    public SupportApplication doneExpired(SimpleRequest request){
        Date today = new Date();

        //判断当前时间是上午还是下午 结果为“0”是上午 结果为“1”是下午
        GregorianCalendar ca = new GregorianCalendar();
        int i = ca.get(GregorianCalendar.AM_PM);
        String time = i == 0 ? "AM" :"PM";

        SupportApplication supportApplication = request.getO(SupportApplication.class);
        List<SupportApplicationItem> supportApplicationItems = supportApplication.getSupportApplicationItems();
        List<SupportApplicationExecution> listExec = new ArrayList<>();
        supportApplicationItems.stream().forEach(item -> {
            if(!item.isIconExecute()){
                Date startDate = item.getStartDate();
                Date endDate = item.getEndDate();
                if (item.getEndTime().getCode().equals("AM")){
                    endDate = DateUtil.parse( DateUtil.format(item.getEndDate(),DateUtil.SHOW_DATE_FORMAT)+" 12:00:00",DateUtil.SHOW_DATETIME_FORMAT);
                }
                if (item.getEndTime().getCode().equals("PM")){
                    endDate = DateUtil.parse( DateUtil.format(item.getEndDate(),DateUtil.SHOW_DATE_FORMAT)+" 23:59:59",DateUtil.SHOW_DATETIME_FORMAT);
                }

                SupportApplicationExecution exec = supportApplicationExecutionRepository.findByTransferApplicationItems(item);

                if(today.getTime() > startDate.getTime() && today.getTime() < endDate.getTime()){
                    listExec.add(exec);
                    item.setIconExecute(true);
                }else if(DateUtils.isSameDay(today,startDate)){
                    //今天的支援明细 当前时间是下午生效时间是下午，并且结束日期未到 执行支援内容
                    if(item.getStartTime().getCode().equals("AM") && time.equals("PM") && today.getTime() < exec.getEndDate().getTime()){
                        listExec.add(exec);
                        item.setIconExecute(true);
                    }
                }else {
                    return;
                }
            }
        });
        updateRYXX(listExec);
        supportApplication.setLastUpdatedStamp(new Date());
        return supportApplicationRepository.saveAndFlush(supportApplication);
    }

    /**
     *  执行 生效 更新人员信息
     * @param listExec
     * @throws RuntimeException
     */
    public void updateRYXX(List<SupportApplicationExecution> listExec) throws RuntimeException{
        listExec.stream().forEach(itemExec -> {
            SupportApplicationItem item = itemExec.getSupportApplicationItem();
            item.setIconExecute(true);
            JSONObject synPerson = new JSONObject();  // 同步旧框架 使用

            //推送钉钉调动同步群组
            SpringManager.getBean(OutboxSubscriberService.class)
                    .commonSendRequest("local:hrDingDingDeptService.transferDingDingForFee",
                            "transferDingDingForFee" + item.getId() , new JSONObject(MapUtil.mapper(
                                    "id", item.getId()
                            )));

            try {
                synPerson = updatePosts(itemExec, synPerson);
            } catch (Exception e) {
                throw new RuntimeException();
            }
        });
    }

    //终止
    public void zzRYXX(List<SupportApplicationExecution> listEnd) throws RuntimeException {
        // 获取有效 要终止 列表
        listEnd.forEach(itemzz -> {

            JSONObject synPerson = new JSONObject();
            String employeeId  = itemzz.getSupportUid().getId(); // 人员编码
            String yItemId = itemzz.getSupportApplicationItem().getId();
            List<SupportApplicationItem> item = supportApplicationItemRepository.findAllById(yItemId);
            SupportApplicationItem yItem = item.get(0);

            //推送钉钉终止操作更新钉钉群组
            SpringManager.getBean(OutboxSubscriberService.class)
                    .commonSendRequest("local:hrDingDingDeptService.restoreDingDingForFee",
                            "restoreDingDingForFee" + yItem.getId() ,
                            new JSONObject(MapUtil.mapper(
                                    "id", yItem.getId()
                            )));
            // 还原 支援时 前 的角色
            String sJsList = yItem.getRoleList();
            User user = userRepository.findByOrigin(yItem.getSupportUid().getOrigin());
            if (user!=null){
                if(sJsList!=null ) {
                    String sRoles = updateUser(user, sJsList);
                    synPerson.put("Roles", sRoles);
                } else {
                    user.setPosts(null);
                    synPerson.put("Roles", null);
                }
                userRepository.saveAndFlush(user);
            }

            updateItemIconExecute(yItem); //终止更新执行标识
        });

    }

    //更新岗位角色
    private JSONObject updatePosts(SupportApplicationExecution itemExec,JSONObject synPerson) throws Exception {
        List<SupportApplicationRole> roleList = itemExec.getSupportApplicationItem().getSupportApplicationRoles();
        StringBuffer sRoleList = new StringBuffer();  // 同步旧框架 使用
        List<String> orginList = new ArrayList<>();
        if(roleList!=null&&roleList.size()>0) {
            //查找 用户
            String sOrigin = itemExec.getSupportUid().getOrigin();
            try{
                User user = userRepository.findByOrigin(sOrigin);
                if(user!=null){
                    // 更新要备份 的 原 item 角色 列表
                    List<Post> postLists = user.getPosts();
                    if (postLists.size()>0) {
                        List<Post> posts = new ArrayList<>();
                        StringBuffer yRoleList = new StringBuffer();
                        postLists.forEach(yRole -> {
                            yRoleList.append(yRole.getId()+";");

                        });
                        updateItem(itemExec,yRoleList.toString());
                    }
                    // 更新 原 item 角色 列表
                    Integer iBid  = user.getId(); //user编码
                    List<Post> posts = new ArrayList<>();
                    roleList.forEach(role -> {
                        String sAid = role.getPostId();
                        Post oldPost = postRepository.findOne(sAid);
                        orginList.add(oldPost.getOrigin());
                        Post post = postRepository.findOne(sAid);
                        posts.add(post);
                    });
                    orginList.stream().distinct().forEach(orgin -> {
                        sRoleList.append(orgin+";");  // 同步旧框架 使用
                    });
                    user.setPosts(posts); // 创建到中间表
                    userRepository.saveAndFlush(user);
                } else{
                    // 没有 操作员的创建
                    SimpleRequest request = new SimpleRequest();
                    User newUser = new User();
                    newUser.setName(itemExec.getSupportUid().getName());
                    newUser.setOrigin(itemExec.getSupportUid().getOrigin());
                    List postLists = new JSONArray();
                    roleList.forEach(role -> {
                        String sAid = role.getPostId();
                        Post oldPost = postRepository.findOne(sAid);
                        orginList.add(oldPost.getOrigin());
                        JSONObject post = new JSONObject();
                        post.put("id",role.getPostId());
                        postLists.add(post);  //
                    });
                    orginList.stream().distinct().forEach(orgin -> {
                        sRoleList.append(orgin+";");  // 同步旧框架 使用
                    });
                    newUser.setPostLits(postLists);
                    request.setData(newUser);
                    userService.save(request);
                }
            }catch(Exception e){
                throw new RuntimeException("更新岗位出错！");
            }
        }
        // 同步旧框架 使用
        synPerson.put("Roles",sRoleList);
        return synPerson;
        // 同步旧框架 使用 END
    }

    // 更新用户岗位
    private String updateUser(User user,String sJsList){
        Integer iBid  = user.getId(); //user编码
        List<Post> posts = new ArrayList<>();
        StringBuffer sRoleList = new StringBuffer();
        String[] sJS = sJsList.toString().split(";");
        for (int f = 0, iLen = sJS.length; f < iLen; f++) {
            String ryjs = sJS[f];
            Post post = postRepository.findOne(ryjs);
            if(post != null ) {
                sRoleList.append(post.getOrigin()+";");  // 同步旧框架 使用
                posts.add(post);
            }

        }
        user.setPosts(posts); // 创建到中间表
        return sRoleList.toString();
    }

    /**
     * 获取 计费支援申请单转审核OA候选人
     * @param supportApplication
     */
    public void getCandidate(SupportApplication supportApplication){
        SupportApplicationDetail detail = supportApplication.getSupportApplicationDetails().get(0);
        String operation = "";
        //运营模式(001072:直营;001071:合伙人;001073:赋能店)
        if (detail.getDept() != null){
            operation = deptRepository.findOperationByDept(detail.getDept().getId());
            if (operation.equals("001073")){
                //出人门店已填写并且运营模式是赋能，OA审核人为该门店店长
                List<Post> posts = postRepository.findAllByBranchIdAndWorkPostId(detail.getDept().getBranch().getId(), "0000016");
                List<User> agents = new ArrayList<>();
                if (!posts.isEmpty()){
                    posts.forEach(post -> {
                        List<User> users = userRepository.findByPost(post.getId());
                        if (!users.isEmpty()) agents.addAll(users);
                    });
                }
                if(!agents.isEmpty()){
                    List<String> users = new ArrayList<>();
                    agents.stream().distinct().forEach(agent -> {
                        users.add(String.valueOf(agent.getId()));
                    });
                    supportApplication.setCandidates(JSONObject.toJSONString(users));
                }
            }
        }
        if (detail.getDept() == null || !operation.equals("001073")){
            //出人门店未填写或者出人门店所属公司的运营模式为直营
            WorkPost workPost = detail.getWorkPost();
            List<User> agents = new ArrayList<>();
            if (workPost.getPostGroup().getId().equals("0005")){
                //支援申请岗位的岗位分组为助理组 下级代办人为财务+督导部
                List<User> users = userRepository.findByPost("A0001");
                List<User> users1 = userRepository.findByPost("A0018");
                List<User> users2 = userRepository.findByPost("00000701");
                if (!users.isEmpty()) agents.addAll(users);
                if (!users1.isEmpty()) agents.addAll(users1);
                if (!users2.isEmpty()) agents.addAll(users2);
            }else if(workPost.getPostGroup().getId().equals("0001")){
                //支援申请岗位的岗位分组为美容组 下级代办人为美容技术经理+督导部
                List<User> users = userRepository.findByPost("A0017");
                List<User> users1 = userRepository.findByPost("A0018");
                if (!users.isEmpty()) agents.addAll(users);
                if (!users1.isEmpty()) agents.addAll(users1);
            }else if(workPost.getPostGroup().getId().equals("0002")){
                //支援申请岗位的岗位分组为机电组 下级代办人为机电技术经理+督导部
                List<User> users = userRepository.findByPost("A0015");
                List<User> users1 = userRepository.findByPost("A0018");
                if (!users.isEmpty()) agents.addAll(users);
                if (!users1.isEmpty()) agents.addAll(users1);
            }else if(workPost.getPostGroup().getId().equals("0006")){
                //支援申请岗位的岗位分组为服务顾问组 下级代办人为督导部
                List<User> users = userRepository.findByPost("A0018");
                if (!users.isEmpty()) agents.addAll(users);
            }else if(workPost.getPostGroup().getId().equals("0004")){
                //支援申请岗位的岗位分组为店长组 下级代办人为督导部
                List<User> users = userRepository.findByPost("A0018");
                if (!users.isEmpty()) agents.addAll(users);
            }else if(workPost.getPostGroup().getId().equals("0003")){
                //支援申请岗位的岗位分组为钣喷组  下级代办人为钣喷技术经理 督导部
                List<User> users = userRepository.findByPost("A0016");
                List<User> users1 = userRepository.findByPost("A0018");
                if (!users.isEmpty()) agents.addAll(users);
                if (!users1.isEmpty()) agents.addAll(users1);
            }else if(workPost.getPostGroup().getId().equals("0009")){
                //支援申请岗位的岗位 为推广 分组为0009 下级代办人为门管技术中心副总裁 督导部
                List<User> users = userRepository.findByPost("A0014");
                List<User> users1 = userRepository.findByPost("A0018");
                if (!users.isEmpty()) agents.addAll(users);
                if (!users1.isEmpty()) agents.addAll(users1);
            }
            if(!agents.isEmpty()){
                List<String> users = new ArrayList<>();
                agents.stream().distinct().forEach(agent -> {
                    users.add(String.valueOf(agent.getId()));
                });
                supportApplication.setCandidates(JSONObject.toJSONString(users));
            }
        }
    }

    /**
     *  检查本地角色
     * @param supportApplication
     */
    public void checkSupportApplicationRoles(SupportApplication supportApplication){
        List<SupportApplicationItem> items = supportApplication.getSupportApplicationItems();
        items.stream().forEach(item -> {
            List<SupportApplicationRole> supportApplicationRoles = item.getSupportApplicationRoles();
            if(supportApplicationRoles.isEmpty()) throw new RuntimeException("支援人员 "+item.getSupportUid().getName()+" 的本地角色不允许为空！！！");
            if (supportApplicationRolesIsRepeat(supportApplicationRoles)) throw new RuntimeException("支援人员 "+item.getSupportUid().getName()+" 的本地角色重复！！！");
            //开始时间为上午 6:00 为下午12:00 结束时间为上午 12:00 下午为23:59:59
            if (item.getStartTime().getCode().equals("AM")){
                item.setStartDate(DateUtil.parse( DateUtil.format(item.getStartDate(),DateUtil.SHOW_DATE_FORMAT)+" 06:00:00",DateUtil.SHOW_DATETIME_FORMAT));
            }
            if (item.getStartTime().getCode().equals("PM")){
                item.setStartDate(DateUtil.parse( DateUtil.format(item.getStartDate(),DateUtil.SHOW_DATE_FORMAT)+" 12:00:00",DateUtil.SHOW_DATETIME_FORMAT));
            }
            if (item.getEndTime().getCode().equals("AM")){
                item.setEndDate(DateUtil.parse( DateUtil.format(item.getEndDate(),DateUtil.SHOW_DATE_FORMAT)+" 12:00:00",DateUtil.SHOW_DATETIME_FORMAT));
            }
            if (item.getEndTime().getCode().equals("PM")){
                item.setEndDate(DateUtil.parse( DateUtil.format(item.getEndDate(),DateUtil.SHOW_DATE_FORMAT)+" 23:59:59",DateUtil.SHOW_DATETIME_FORMAT));
            }
        });
    }

    /**
     * 判断 List<SupportApplicationRole> 的本地角色 是否有重复,重复返回true
     * @param supportApplicationRoles
     * @return
     */
    private Boolean supportApplicationRolesIsRepeat(List<SupportApplicationRole> supportApplicationRoles) {
        Set<SupportApplicationRole> set = new TreeSet<SupportApplicationRole>(new Comparator<SupportApplicationRole>() {
            public int compare(SupportApplicationRole a, SupportApplicationRole b) {
                // 字符串则按照asicc码升序排列
                return a.getPostId().compareTo(b.getPostId());
            }
        });
        set.addAll(supportApplicationRoles);
        if (set.size() < supportApplicationRoles.size()) {
            return true;
        }
        return false;
    }

    /**
     * 检查和调动，支援单是否有冲突
     */
    public void checkTransferClash(SupportApplication supportApplication){
        List<SupportApplicationItem> items = supportApplication.getSupportApplicationItems();
        items.stream().forEach(item -> {

            //没有执行的支援单从支援人员明细取
            List<SupportApplicationItem> supports = supportApplicationItemRepository.findBySupportUidAndIconExecuteAndRepeal(item.getSupportUid(),false,false);
            if (!supports.isEmpty()){
                SupportApplicationItem oldItem = supports.get(selectLastOne2(supports));
                //新单的生效日期小于等于旧单的生效日期 && 新单的结束支援日期 大于 旧单生效日期 提示
                if(item.getStartDate().getTime()<= oldItem.getStartDate().getTime()
                        && item.getEndDate().getTime()> oldItem.getStartDate().getTime()){
                    throw new RuntimeException(item.getSupportUid().getName() +"与支援申请单：" + oldItem.getSupportApplication().getId() + "冲突！支援前不可支援！");
                    //新单的生效日期大于旧单的生效日期 && 新单的生效日期 小于等于 旧单支援结束日期
                } else if (item.getStartDate().getTime() >oldItem.getStartDate().getTime()
                        &&item.getStartDate().getTime()<= oldItem.getEndDate().getTime() ){
                    throw new RuntimeException(item.getSupportUid().getName() +"与支援申请单：" + oldItem.getSupportApplication().getId() + "冲突！不可在支援期间支援！");
                    //新单的生效日期小于旧单的生效日期 && 新单的支援结束日期 大于 旧单支援结束日期
                } else if (item.getStartDate().getTime() < oldItem.getStartDate().getTime()
                        &&item.getEndDate().getTime() > oldItem.getEndDate().getTime() ){
                    throw new RuntimeException(item.getSupportUid().getName() +"与支援申请单：" + oldItem.getSupportApplication().getId() + "冲突！不可在支援期间支援！");
                    //新单的生效日期小于等于旧单的生效日期 && 新单的结束支援日期大于等于旧单的生效日期
                }else if (item.getStartDate().getTime() <= oldItem.getStartDate().getTime()
                        && item.getEndDate().getTime() >= oldItem.getStartDate().getTime()){
                    throw new RuntimeException(item.getSupportUid().getName() +"与支援申请单：" + oldItem.getSupportApplication().getId() + "冲突！");
                }
            }

            //已经执行的支援单从执行表里取数
            List<SupportApplicationExecution> listExec = supportApplicationExecutionRepository.findBySupportApplication(item.getSupportUid().getId());

            if(!listExec.isEmpty()){
                listExec.stream().forEach(exec -> {
                    if(item.getStartDate().getTime() <= exec.getStartDate().getTime() && item.getStartDate().getTime() > exec.getEndDate().getTime()){
                        throw new RuntimeException(item.getSupportUid().getName() +"与付费支援申请单：" + exec.getSupportApplicationItem().getSupportApplication().getId() + "冲突！支援前不可支援！");
                    } else if (item.getStartDate().getTime() >exec.getStartDate().getTime()
                            &&item.getStartDate().getTime()< exec.getEndDate().getTime() ){
                        throw new RuntimeException(item.getSupportUid().getName() +"与付费支援申请单：" + exec.getSupportApplicationItem().getSupportApplication().getId() + "冲突！不可在支援期间支援！");
                        //新单的生效日期小于旧单的生效日期 && 新单的支援结束日期 大于 旧单支援结束日期
                    } else if (item.getStartDate().getTime() < exec.getStartDate().getTime()
                            &&item.getEndDate().getTime() > exec.getEndDate().getTime() ){
                        throw new RuntimeException(item.getSupportUid().getName() +"与付费支援申请单：" + exec.getSupportApplicationItem().getSupportApplication().getId() + "冲突！不可在支援期间支援！");
                        //新单的生效日期小于等于旧单的生效日期 && 新单的结束支援日期大于等于旧单的生效日期
                    }else if (item.getStartDate().getTime() <= exec.getStartDate().getTime()
                            && item.getEndDate().getTime() >= exec.getStartDate().getTime()){
                        throw new RuntimeException(item.getSupportUid().getName() +"与付费支援申请单：" + exec.getSupportApplicationItem().getSupportApplication().getId() + "冲突！");
                    }
                });
            }

            //根据计费支援单的开始时间判断是否和调动单有冲突
            List<TransferApplicationItem>  timeOutItems = transferApplicationItemRepository.findByTransferUidAndIconExecuteAndEffectiveDate(item.getSupportUid(),true,item.getStartDate());
            if (!timeOutItems.isEmpty()){
                timeOutItems.forEach(timeOutItem->{
                    if (timeOutItem.getTransferApplications().getHrTransferType().equals("000102")){
                        throw new RuntimeException(item.getSupportUid().getName() +"与调动申请单：" + timeOutItems.get(timeOutItems.size()-1).getTransferApplications().getId() + "冲突");
                    }
                });
            }

            //未执行且未废除的调动 支援单
            List<TransferApplicationItem>  Items = transferApplicationItemRepository.findByTransferUidAndIconExecute(item.getSupportUid(),false);
            List<TransferApplicationItem>  itemList= new ArrayList<>();
            if (!Items.isEmpty()){
                Items.forEach(Item->{
                    String state= Item.getTransferApplications().getState();
                    if (!(state.equals("repeal")||state.equals("delete")||Item.getId().equals(item.getId()))&&!Item.isRepeal()){
                        itemList.add(Item);
                    }
                });
            }

            //执行还未结束支援的支援单
            List<TransferApplicationItem> supItemList =  transferApplicationItemRepository.findByTransferUidAndIconExecute(item.getSupportUid(),true);
            if(!supItemList.isEmpty()){
                supItemList.forEach(supItem->{
                    if (supItem.getTransferApplications().getHrTransferType().getId().equals("000103")
                            && !supItem.getHrTransferKind().getId().equals("000430") //不等于临时调工号
                            && supItem.getEndDate().getTime() > new Date().getTime()
                            && supItem.getTransferUid().equals(item.getSupportUid())
                            &&( !supItem.getTransferApplications().getState().equals("repeal")
                            || !supItem.getTransferApplications().getState().equals("delete"))
                            &&!supItem.isRepeal()){
                        itemList.add(supItem);
                    }
                });
            }

            if (!itemList.isEmpty()){
                TransferApplicationItem oldItem = itemList.get(selectLastOne(itemList));
                String oldType =oldItem.getTransferApplications().getHrTransferType().getId();
                if(oldType.equals("000102")){
                    //新单的生效日期小于等于旧单的生效日期 && 新单的支援结束日期 大于等于 旧单生效日期
                    if (item.getStartDate().getTime() <= oldItem.getEffectiveDate().getTime()&&
                            item.getEndDate().getTime() >= oldItem.getEffectiveDate().getTime()){
                        throw new RuntimeException( item.getSupportUid().getName() +"与调动申请单：" + oldItem.getTransferApplications().getId() + "冲突");
                    }
                }else if (oldType.equals("000103")){
                    //新单的生效日期小于等于旧单的生效日期 && 新单的结束支援日期 大于 旧单生效日期 提示
                    if(item.getStartDate().getTime()<= oldItem.getEffectiveDate().getTime()
                            && item.getEndDate().getTime()> oldItem.getEffectiveDate().getTime()){
                        throw new RuntimeException(item.getSupportUid().getName() +"与支援申请单：" + oldItem.getTransferApplications().getId() + "冲突！支援前不可支援！");
                        //新单的生效日期大于旧单的生效日期 && 新单的生效日期 小于等于 旧单支援结束日期
                    } else if (item.getStartDate().getTime() >oldItem.getEffectiveDate().getTime()
                            &&item.getStartDate().getTime()<= oldItem.getEndDate().getTime() ){
                        throw new RuntimeException(item.getSupportUid().getName() +"与支援申请单：" + oldItem.getTransferApplications().getId() + "冲突！不可在支援期间支援！");
                        //新单的生效日期小于旧单的生效日期 && 新单的支援结束日期 大于 旧单支援结束日期
                    } else if (item.getStartDate().getTime() < oldItem.getEffectiveDate().getTime()
                            &&item.getEndDate().getTime() > oldItem.getEndDate().getTime() ){
                        throw new RuntimeException(item.getSupportUid().getName() +"与支援申请单：" + oldItem.getTransferApplications().getId() + "冲突！不可在支援期间支援！");
                        //新单的生效日期小于等于旧单的生效日期 && 新单的结束支援日期大于等于旧单的生效日期
                    }else if (item.getStartDate().getTime() <= oldItem.getEffectiveDate().getTime()
                            && item.getEndDate().getTime() >= oldItem.getEffectiveDate().getTime()){
                        throw new RuntimeException(item.getSupportUid().getName() +"与支援申请单：" + oldItem.getTransferApplications().getId() + "冲突！");
                    }
                }
            }
        });



    }

    /**
     * 写入执行表
     */
    public void insertExecution(SupportApplicationItem item){
        SupportApplicationExecution iExec = new SupportApplicationExecution();
        iExec.setSupportApplicationItem(item);
        iExec.setSupportUid(item.getSupportUid());
        iExec.setBranch(item.getBranchAfter());
        iExec.setWorkPost(item.getWorkPostAfter());
        iExec.setJob(item.getJobAfter());
        iExec.setStartDate(item.getStartDate());
        iExec.setStartTime(item.getStartTime());
        iExec.setEndDate(item.getEndDate());
        iExec.setEndTime(item.getEndTime());
        iExec.setSupportDays(item.getSupportDays());
        iExec.setTollCase(item.isTollCase());
        iExec.setTollAmt(item.getTollAmt());
//        iExec.setTollTotalAmt(item.getTollTotalAmt());
        iExec.setDiscountsAmt(item.getDiscountsAmt());
//        iExec.setDiscountsTotalAmt(item.getDiscountsTotalAmt());
        iExec.setActualPayAmt(item.getActualPayAmt());
        supportApplicationExecutionRepository.saveAndFlush(iExec);
    }

    /**
     * 创建时检查数据
     * @param request
     */
    public void checkData(SimpleRequest request) {
        String id = request.get("id");
        SupportApplication supportApplication = supportApplicationRepository.findOne(id);
        if (supportApplication == null) throw new RuntimeException("计费支援申请单【" + id + "】在系统中不存在。");
    }

    /**
     * 创建日期最大的明细
     * @param list
     * @return
     */
    private int selectLastOne(List<TransferApplicationItem> list) {
        int index = 0;
        Long dates[] = new Long[list.size()];
        for (int i = 1; i <= list.size(); i++) {
            // 把date类型的时间对象转换为long类型，时间越往后，long的值就越大，
            // 所以就依靠这个原理来判断距离现在最近的时间
            dates[i - 1] = list.get(i-1).getCreateDate().getTime();
        }

        Long maxIndex = dates[0];// 定义最大值为该数组的第一个数
        for (int j = 0; j < dates.length; j++) {
            if (maxIndex < dates[j]) {
                maxIndex = dates[j];
                // 找到了这个j
                index = j;
            }
        }
        return index;
    }

    /**
     * 创建日期最大的明细
     * @param list
     * @return
     */
    private int selectLastOne2(List<SupportApplicationItem> list) {
        int index = 0;
        Long dates[] = new Long[list.size()];
        for (int i = 1; i <= list.size(); i++) {
            // 把date类型的时间对象转换为long类型，时间越往后，long的值就越大，
            // 所以就依靠这个原理来判断距离现在最近的时间
            dates[i - 1] = list.get(i-1).getCreateDate().getTime();
        }

        Long maxIndex = dates[0];// 定义最大值为该数组的第一个数
        for (int j = 0; j < dates.length; j++) {
            if (maxIndex < dates[j]) {
                maxIndex = dates[j];
                // 找到了这个j
                index = j;
            }
        }
        return index;
    }

    /**
     * 获取策略金额 收费金额
     * @param request 岗位和职位 维度
     * @return
     */
    public double getStrategyQty(SimpleRequest request){
        String workPostId = request.get("workPost");
        String jobId = request.get("job");
        String hrTransferKind = request.get("hrTransferKind");
        String id = request.get("strategyId");
        String operation = request.get("operation");
        String fnTag = request.get("fnTag");

        Map map = MapUtil.mapper(
                "WORK_POST_ID", workPostId, "JOB_ID", jobId, "SUPPORT_TYPE", hrTransferKind, "OPERATION", operation, "FN_TAG", fnTag, "SYS_RQ", new Date(), "conditionStrategyId", id
        );
        Object obj = this.invoke("condition.execConditionStrategy", map);
        JSONObject result = new JSONObject(MapUtil.mapped(obj));
        return result.getDoubleValue("T001");
    }

    /**
     * 功能：更新 角色
     * @param
     */
    public void updateItem(SupportApplicationExecution itemExec,String yRoleList){
        String itemId  = itemExec.getSupportApplicationItem().getId();
        supportApplicationItemRepository.updateItemRoles(yRoleList, itemId);
    }

    /**
     * 功能：保存 更新执行标识 为真
     * @param
     */
    public void updateItemIconExecute(SupportApplicationItem item){
        supportApplicationItemRepository.updateItemIconExecute(item.getId(),true);
    }
}
